<?php

require_once(dirname(__FILE__).'/People.php');
require_once(dirname(__FILE__).'/Constants.php');
require_once(dirname(__FILE__).'/Config.php');
require_once(dirname(__FILE__).'/MemberCache.php');

class HimaShare {

    function get_member ($member_id) {
        if ($member = MemberCache::get_member($member_id)) {
            return $member;
        }

        $appli_id     = APP_ID_MB;
        $member       = array_pop(People::get_self($member_id, $appli_id));
        $member       = $member['person'];
        if (!$member_id) return;
        $id           = array_pop(explode(':', $member['id']));
        $member['id'] = $id;

        MemberCache::set_member($member);

        return $member;
    }

    function get_friends ($member_id) {
        $friends = array();
        if ($friends_cache = MemberCache::get_optin_friends($member_id)) {
            $friends = $friends_cache;
        }
        else {
            $appli_id_list = array (
                APP_ID_PC, APP_ID_MB
            );

            foreach ($appli_id_list as $appli_id) {
                $friends_per_appli = People::get_optin_friends(
                    $member_id, $appli_id
                );
                foreach ($friends_per_appli as $friend) {
                    $friend = $friend['person'];
                    $id = array_pop(explode(':', $friend['id']));
                    $friend['id'] = $id;
                    $friends[] = $friend;
                }
            }
            MemberCache::set_optin_friends($member_id, $friends);
        }

        $friend_hash = array();
        foreach ($friends as $friend) {
            $friend_hash[$friend['id']] = $friend;
        }
        return $friend_hash;
    }

    function get_all_friends ($member_id) {
        $friends = array();
        if ($friends_cache = MemberCache::get_friends($member_id)) {
            $friends = $friends_cache;
        }
        else {
            $appli_id_list = array (
                APP_ID_PC, APP_ID_MB
            );

            foreach ($appli_id_list as $appli_id) {
                $friends_per_appli = People::get_friends(
                    $member_id, $appli_id
                );
                foreach ($friends_per_appli as $friend) {
                    $friend = $friend['person'];
                    $id = array_pop(explode(':', $friend['id']));
                    $friend['id'] = $id;
                    $friends[] = $friend;
                }
            }
            MemberCache::set_friends($member_id, $friends);
        }
        $friend_hash = array();
        foreach ($friends as $friend) {
            $friend_hash[$friend['id']] = $friend;
        }
        return $friend_hash;
    }
}
